﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

using PowerCreator.LMS.Common.Script;
using PowerCreator.LMS.Web.CMS;
using PowerCreator.LMS.CMS.Entity;
using PowerCreator.LMS.Common.Utils;
using Telerik.WebControls;
using PowerCreator.LMS.Web;


public partial class sysadmin_NewManager_AddNew : PowerCreator.LMS.Web.Base.WebBasePage
{
    New objNew = new New();
    PowerCreator.LMS.Web.Course.Course opCourse = new PowerCreator.LMS.Web.Course.Course();
    private PowerCreator.LMS.Web.DL.User.LoginEntity login = new PowerCreator.LMS.Web.DL.User.LoginEntity();
    private string url = "../login.aspx";

    protected void Page_Load(object sender, EventArgs e)
    {
        //if (IsLicensed(PowerCreator.LMS.Action.Core.ActionInfo.AddJob))
        //{
        //    Script.RedirectURL(GetRefUrl());
        //}
        CheckUser();
        if (!IsPostBack)
        {
           
            InitPage();
            BinderNewType();
            int NewID = 0; 
            if (Request.QueryString["NewID"] != null)
            {
                NewID = int.Parse(Request.QueryString["NewID"].ToString());
                ViewState["NewID"] = NewID.ToString();
                BinderForm(NewID);
            }
            BindRpt();
        }
        
            //LinkButton lnkbtn_del1 = (LinkButton)e.Item.FindControl("lnkbtn_del");
            //lnkbtn_del1.Attributes.Add("onClick", "javascript:return confirm('确定删除此记录？')");

        
    }

    private void CheckUser()
    {
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] == null)
        {
            Script.RedirectNewUrl(url);
        }
        else
        {
            login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
            if (login == null)
            {
                Script.RedirectNewUrl(url);
            }
            else
            {
                if (login.VOAdvancedUser == null)
                {
                    Script.RedirectNewUrl(url);
                }
                else if (login.VOAdvancedUser.AUserGroup > 3)
                {
                    //Response.Write(login.VOAdvancedUser.AUserGroup.ToString());
                    //Response.End();
                    Script.ShowAndHistory("您无此权限！", -1);
                }
            }
        }


    }
    protected override void InitPage()
    {
        //lbl_InfoTitle.Text = GetLanageValueByKey("lbl_AddJob_InfoTitle", PowerCreator.LMS.Language.LanagetItemType.Page);
        //lbl_JobName.Text = GetLanageValueByKey("lbl_AddJob_JobName", PowerCreator.LMS.Language.LanagetItemType.Page);
        //lbl_JobDescription.Text = GetLanageValueByKey("lbl_AddJob_JobDescription", PowerCreator.LMS.Language.LanagetItemType.Page);

        //btnSave.Text = GetLanageValueByKey("btn_Save", PowerCreator.LMS.Language.LanagetItemType.Page);
        //btnReset.Text = GetLanageValueByKey("btn_Reset", PowerCreator.LMS.Language.LanagetItemType.Page);
        //base.InitPage();
        string allowExtensions = "gif|jpg";    //允许上传的类型

        lbl_InfoTitle_AddNew.Text = GetLanageValueByKey("lab_AddNew_AddNews", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewBaseInfo.Text = GetLanageValueByKey("lab_AddNew_NewsSet", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewAttributeInfo.Text = GetLanageValueByKey("lab_AddNew_OtherNewsSet", PowerCreator.LMS.Language.LanagetItemType.Page);
        //lbl_NewUploadInfo.Text = "新闻相关文件上传";
        lbl_NewTitle.Text = GetLanageValueByKey("lab_AddNew_NewsTitle", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewSubhead.Text = GetLanageValueByKey("lab_AddNew_NewsShortTitle", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewContent.Text = GetLanageValueByKey("lab_AddNew_NewsContent", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewNewType.Text = GetLanageValueByKey("lab_AddNew_NewsType", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewKeyword.Text = GetLanageValueByKey("lab_AddNew_Guanjianci", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewAuthor.Text = GetLanageValueByKey("lbl_AddResourceInfo_AuthorName", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewSource.Text = GetLanageValueByKey("lab_AddNew_NewsSourse", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewIsTop.Text = GetLanageValueByKey("lab_AddNew_IsTop", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_NewTrainClaID.Text = "面向班级";
        cb_NewIsTop.Text = "";

        lbl_msg_description.Text = GetLanageValueByKey("AddCourseInfo_lbl_l1", PowerCreator.LMS.Language.LanagetItemType.Page);
        //lbl_NewFileUrl.Text = "附件";
        //lbl_NewPictureUrl.Text = "图片";
        //lbl_NewPictureUrl_intro.Text = "只有在前台页面做特殊展示，例如做图片新闻时才需上传！";
        lbl_FileUpload_msg_FileType.Text = "注意：" + GetLanageValueByKey("AddCourseInfo_msg_m2", PowerCreator.LMS.Language.LanagetItemType.Page) + allowExtensions;

        btnSave.Text = GetLanageValueByKey("btn_Save", PowerCreator.LMS.Language.LanagetItemType.Page);
        btnReset.Text = GetLanageValueByKey("btn_Reset", PowerCreator.LMS.Language.LanagetItemType.Page);
        base.InitPage();
    }
    private void BinderNewType()
    {
        DataTable dt = new DataTable();
        NewType objType = new NewType();
        dt = objType.Query("");
        ddl_FKNewNewTypeID.DataSource = dt;
        ddl_FKNewNewTypeID.DataTextField = "NewTypeName";
        ddl_FKNewNewTypeID.DataValueField = "NewTypeID";
        ddl_FKNewNewTypeID.DataBind();

    }
    /// <summary>
    /// 绑定培训班信息
    /// </summary>
    private void BindRpt()
    {
        PowerCreator.LMS.Web.DL.Project.TOClass obj = new PowerCreator.LMS.Web.DL.Project.TOClass();

        Hashtable hs = new Hashtable();
        ArrayList list = new ArrayList();

        if (ViewState["NewID"] != null)
        {

            string search = string.Format("NewID={0}", ViewState["NewID"].ToString());
            DataTable dt2 = objNew.Query(search);
            if(dt2.Rows.Count==1)
            {
                string[] trainclaIDs = dt2.Rows[0]["FKNewTrainclaIDList"].ToString().Split(',');
                for (int i = 0; i < trainclaIDs.Length; i++)
                {
                    hs.Add(trainclaIDs[i].ToString(), "1");
                }
            }

        }

        DataTable dt = obj.Query("");
        chk_FKNewClaIDlist.DataSource = dt;
        chk_FKNewClaIDlist.DataTextField = "Name";
        chk_FKNewClaIDlist.DataValueField = "class_id";
        chk_FKNewClaIDlist.DataBind();

        if (ViewState["NewID"] != null)
        {
            for (int j = 0; j < chk_FKNewClaIDlist.Items.Count; j++)
            {
                if (hs.ContainsKey(chk_FKNewClaIDlist.Items[j].Value))
                    chk_FKNewClaIDlist.Items[j].Selected = true;
            }
        }



        //PowerCreator.LMS.Web.Project.ProjectUser opProClass = new PowerCreator.LMS.Web.Project.ProjectUser();
        //PowerCreator.LMS.Web.CMS.New opNew = new New();
        //PowerCreator.LMS.Web.Project.Project opPro = new PowerCreator.LMS.Web.Project.Project();
        //DataTable dt = opPro.QueryTrainProject("");
        //rptTrainClassIDlist.DataSource = dt;
        //rptTrainClassIDlist.DataBind();

        //Hashtable hs = new Hashtable();
        //ArrayList list = new ArrayList();

        //if (ViewState["NewID"] != null)
        //{

        //    string search = string.Format("NewID={0}", ViewState["NewID"].ToString());
        //    DataTable dt2 = opNew.Query(search);
        //    if (dt2.Rows.Count == 1)
        //    {
        //        string[] trainclaIDs = dt2.Rows[0]["FKNewTrainclaIDList"].ToString().Split(',');
        //        for (int i = 0; i < trainclaIDs.Length; i++)
        //        {
        //            hs.Add(trainclaIDs[i].ToString(), "1");
        //        }
        //    }

        //}

        //for (int i = 0; i < rptTrainClassIDlist.Items.Count; i++)
        //{
        //    CheckBoxList chkList = (CheckBoxList)rptTrainClassIDlist.Items[i].FindControl("chk_FKNewTrainClaIDlist");
        //    Label lbl_ProID = (Label)rptTrainClassIDlist.Items[i].FindControl("lbl_ProID");
        //    DataTable dt1 = opProClass.QueryProjectClass("FKTrainclaTrainproID=" + lbl_ProID.Text);

        //    chkList.DataSource = dt1;
        //    chkList.DataTextField = "TrainclaName";
        //    chkList.DataValueField = "TrainclaID";
        //    chkList.DataBind();

        //    if (ViewState["NewID"] != null)
        //    {
        //        for (int j = 0; j < chkList.Items.Count; j++)
        //        {
        //            if (hs.ContainsKey(chkList.Items[j].Value))
        //                chkList.Items[j].Selected = true;
        //        }
        //    }

        //}

    }
    private void BinderForm(int id)
    {
        VOTNew vo = new VOTNew();
        vo = objNew.Load(id);
        txt_NewTitle.Text = vo.NewTitle;
        txt_NewSubhead.Text = vo.NewSubhead;
        ftb_NewContent.Text = vo.NewContent;
        ddl_FKNewNewTypeID.SelectedValue = vo.FKNewNewTypeID.ToString();
        txt_NewKeyword.Text = vo.NewKeyword;
        txt_NewAuthor.Text = vo.NewAuthor;
        txt_NewSource.Text = vo.NewSource;
        txt_pic.Text = vo.NewPictureUrl;
        if (vo.NewIsTop == true)
            cb_NewIsTop.Checked = true;
    }
    private bool CheckPageData()
    {
        string search = string.Format("NewTitle = '{0}'", txt_NewTitle.Text.Trim());
        if (ViewState["NewID"] != null)
        {
            search += "and NewID<>" + ViewState["NewID"].ToString();
        }
        if (objNew.Count(search) != 0)
        {

            //lbl_msg_Error.Text = GetLanageValueByKey("lbl_msg_addjob_aspx_count", PowerCreator.LMS.Language.LanagetItemType.MSG);

            lbl_msg_Error.Text = "<br />" + GetLanageValueByKey("msg_AddNew_msg", PowerCreator.LMS.Language.LanagetItemType.Page); 
            return false;
        }
        return true;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!CheckPageData()) return;
        VOTNew vo = new VOTNew();
        if (ViewState["NewID"] != null)
        {
            vo = objNew.Load(int.Parse(ViewState["NewID"].ToString()));
        }
        vo.NewTitle = txt_NewTitle.Text.Trim();
        vo.NewSubhead = txt_NewSubhead.Text.Trim();
        vo.NewContent = ftb_NewContent.Text;
        vo.FKNewNewTypeID = int.Parse(ddl_FKNewNewTypeID.SelectedValue);
        vo.FKNewTrainclaIDList = getTrainClaIDlist();
        vo.NewKeyword = txt_NewKeyword.Text.Trim();
        vo.NewAuthor = txt_NewAuthor.Text.Trim();
        vo.NewSource = txt_NewSource.Text.Trim();
        vo.NewPictureUrl = txt_pic.Text;
        vo.NewClickNum = 0;
        if (cb_NewIsTop.Checked == true)
            vo.NewIsTop = true;
        vo.NewAddTime = DateTime.Now;

        PowerCreator.LMS.Web.Base.BasePage bpage = new PowerCreator.LMS.Web.Base.BasePage();
        vo.FKNewCreatorid = bpage.GetLoginEntity.UserID;
        vo.NewCreatorname = bpage.GetLoginEntity.RealName;

        if (ViewState["NewID"] == null)
        {
            int newid = 0;
            if (objNew.Add(vo,ref newid))
            {
                CreateNewFile(newid);
                string url = "ManagerNew.aspx";
                Script.RedirectURL(url);
            }
        }
        else
        {
            if (objNew.Update(vo))
            {
                CreateNewFile(vo.NewID);
                string url = "ManagerNew.aspx";
                Script.RedirectURL(url);
            }
        }
    }

    private string getTrainClaIDlist()
    {
        string trainClaIDlist = "-1,";

        for (int j = 0; j < chk_FKNewClaIDlist.Items.Count; j++)
        {
            if (chk_FKNewClaIDlist.Items[j].Selected)
            {
                trainClaIDlist += chk_FKNewClaIDlist.Items[j].Value + ",";
            }
        }
        trainClaIDlist += "0";
        if (trainClaIDlist == "-1,0")
            trainClaIDlist = "";
        return trainClaIDlist;
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        string url = "ManagerNew.aspx";
        Script.RedirectURL(url);
    }



    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //btn_Back.Enabled = false;
        foreach (UploadedFile file in RadUploadContext.Current.UploadedFiles)
        {
            string Url = "";
            Url = WebUtils.WebRoot + "/fileManager/UploadFile/CoursePic/";
            string Path = Server.MapPath(Url);

            //如果路径不存在，则创建
            if (System.IO.Directory.Exists(Path) == false)
            {
                System.IO.Directory.CreateDirectory(Path);
            }

            string filetype = file.GetExtension();
            if (!IsUploadFileType(filetype)) return;

            //组合路径，file.GetName()取得文件名
            string fileName = opCourse.GetUploadResourceFileName(file.GetExtension());

            Path = Path + fileName;
            Url = Url + fileName;
            //保存
            file.SaveAs(Path, true);
            txt_pic.Text = Url;
            btn_Back.Enabled = true;
        }
    }

    //检查上传文件类型
    public bool IsUploadFileType(string extension)
    {
        string allowExtensions = "gif|jpg";    //允许上传的类型
        if (!opCourse.IsAllowedExtension(extension, allowExtensions))
        {
            //lbl_FileUpload_msg_FileType.Text = "注意："+GetLanageValueByKey("AddCourseInfo_msg_m2", PowerCreator.LMS.Language.LanagetItemType.Page) + allowExtensions;
            return false;
        }
        return true;
    }


    
    private void CreateNewFile(int newid)
    {
        string fileurl = "";
        string newfileurl = "";

        //获取当前新闻模板文件路径
        VOTNew vo = new VOTNew();
        vo = objNew.Load(newid);
        if (vo.FKNewNewTypeID != null)
        {
            VOTNewTemplet voNT = new VOTNewTemplet();
            NewTemplet objNT = new NewTemplet();
            voNT = objNT.Load(vo.FKNewNewTypeID);
            if (voNT.Url != null)
                fileurl = voNT.Url;
        }


        try
        {


            if (fileurl.Length > 0)
            {
                string filePath = HttpContext.Current.Server.MapPath(fileurl);

                if (System.IO.File.Exists(filePath))
                {
                    string newfile = System.IO.File.ReadAllText(filePath, System.Text.Encoding.Default);
                    while (newfile.IndexOf("&Title&") > 0)
                        newfile = newfile.Replace("&Title&", vo.NewTitle);
                    while (newfile.IndexOf("&NewSubhead&") > 0)
                        newfile = newfile.Replace("&NewSubhead&", vo.NewSubhead);
                    while (newfile.IndexOf("&NewCreatorname&") > 0)
                        newfile = newfile.Replace("&NewCreatorname&", vo.NewCreatorname);
                    while (newfile.IndexOf("&TimePublish&") > 0)
                        newfile = newfile.Replace("&TimePublish&", vo.NewAddTime.ToString());
                    while (newfile.IndexOf("&NewSource&") > 0)
                        newfile = newfile.Replace("&NewSource&", vo.NewSource);
                    while (newfile.IndexOf("&NewAuthor&") > 0)
                        newfile = newfile.Replace("&NewAuthor&", vo.NewAuthor);
                    while (newfile.IndexOf("&NewKeyword&") > 0)
                        newfile = newfile.Replace("&NewKeyword&", vo.NewKeyword);
                    while (newfile.IndexOf("&NewPictureUrl&") > 0)
                        newfile = newfile.Replace("&NewPictureUrl&", vo.NewPictureUrl);
                    while (newfile.IndexOf("&NewContent&") > 0)
                        newfile = newfile.Replace("&NewContent&", vo.NewContent);

                    string newfilepath = "../../fileManager/Html/CreateNewFile/" + vo.FKNewNewTypeID + "/";

                    string filetype = ".html";
                    string fileName = opCourse.GetUploadResourceFileName(filetype);
                    newfileurl = newfilepath + fileName;
                    newfilepath = HttpContext.Current.Server.MapPath(newfilepath);
                    //如果路径不存在，则创建
                    if (System.IO.Directory.Exists(newfilepath) == false)
                    {
                        System.IO.Directory.CreateDirectory(newfilepath);
                    }
                    newfilepath = newfilepath + fileName;
                    System.IO.File.WriteAllText(newfilepath, newfile, System.Text.Encoding.Default);

                }

            }
            //}
        }
        catch (System.Exception ex)
        {
            Response.Write(ex);
            Response.End();

        }

        vo.NewUrl = newfileurl;
        objNew.Update(vo);
    }
}
